package com.apps.image;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.InputStream;

/**
 * 图片相似度比较
 */
public class ImagesSimilarHelper {

    /**
     * 图片缩放尺寸,px为单位
     */
    private static int size = 32;

    private static int smallerSize = 8;

    private static double[] c;

    private static ColorConvertOp colorConvert = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);

    static
    {
        c = new double[size];
        for (int i = 1; i < size; i++) {
            c[i] = 1;
        }
        c[0] = 1 / Math.sqrt(2.0);
    }

    /**
     * 计算phash的距离,大于10基本上就不是同一张图片了,但如果小于15可做进一步文字内容对比.
     * @param s1
     * @param s2
     * @return
     */
    public static int distance(String s1, String s2)
    {
        int counter = 0;
        for (int k = 0; k < s1.length();k++) {
            if(s1.charAt(k) != s2.charAt(k)) {
                counter++;
            }
        }
        return counter;
    }

    /**
     * 计算图片的phash
     * @param is
     * @return
     * @throws Exception
     */
    public static String getPhash(InputStream is) throws Exception
    {
        BufferedImage img = ImageIO.read(is);
        //缩放
        img = Thumbnails.of(img).size(size,size).asBufferedImage();
        //转为灰度图
        colorConvert.filter(img, img);

        //转为蓝色通道
        double[][] vals = new double[size][size];

        for (int x = 0; x < img.getWidth(); x++) {
            for (int y = 0; y < img.getHeight(); y++) {
                vals[x][y] = getBlue(img, x, y);
            }
        }
        //计算dct
        double[][] dctVals = applyDCT(vals);

        double total = 0;

        for (int x = 0; x < smallerSize; x++) {
            for (int y = 0; y < smallerSize; y++) {
                total += dctVals[x][y];
            }
        }
        total -= dctVals[0][0];

        double avg = total / (double) ((smallerSize * smallerSize) - 1);

        //计算phash
        String hash = "";

        for (int x = 0; x < smallerSize; x++) {
            for (int y = 0; y < smallerSize; y++) {
                if (x != 0 && y != 0) {
                    hash += (dctVals[x][y] > avg?"1":"0");
                }
            }
        }

        return hash;
    }

    /**
     * 计算图片的phash
     * @param img
     * @return
     * @throws Exception
     */
    public static String getPhash(BufferedImage img) throws Exception
    {
        //缩放
        img = Thumbnails.of(img).size(size,size).asBufferedImage();
        //转为灰度图
        colorConvert.filter(img, img);

        //转为蓝色通道
        double[][] vals = new double[size][size];

        for (int x = 0; x < img.getWidth(); x++) {
            for (int y = 0; y < img.getHeight(); y++) {
                vals[x][y] = getBlue(img, x, y);
            }
        }
        //计算dct
        long start = System.currentTimeMillis();
        double[][] dctVals = applyDCT(vals);
//        System.out.println("DCT执行时间: " + (System.currentTimeMillis() - start));

        double total = 0;

        for (int x = 0; x < smallerSize; x++) {
            for (int y = 0; y < smallerSize; y++) {
                total += dctVals[x][y];
            }
        }
        total -= dctVals[0][0];

        double avg = total / (double) ((smallerSize * smallerSize) - 1);

        //计算phash
        String hash = "";

        for (int x = 0; x < smallerSize; x++) {
            for (int y = 0; y < smallerSize; y++) {
                if (x != 0 && y != 0) {
                    hash += (dctVals[x][y] > avg?"1":"0");
                }
            }
        }

        return hash;
    }

    /**
     * 转为蓝色通道
     * @param img
     * @param x
     * @param y
     * @return
     */
    private static   int getBlue(BufferedImage img, int x, int y)
    {
        return (img.getRGB(x, y)) & 0xff;
    }

    private static double[][] applyDCT(double[][] f)
    {
        int N = size;
        double[][] F = new double[N][N];
        for (int u=0;u<N;u++) {
            for (int v=0;v<N;v++) {
                double sum = 0.0;
                for (int i=0;i<N;i++) {
                    for (int j=0;j<N;j++) {
                        sum+=Math.cos(((2*i+1)/(2.0*N))*u*Math.PI)*Math.cos(((2*j+1)/(2.0*N))*v*Math.PI)*(f[i][j]);
                    }
                }
                sum*=((c[u]*c[v])/4.0);
                F[u][v] = sum;
            }
        }
        return F;
    }
}
